﻿using AVCUMPlatform.Entities;
using AVCUMPlatform.HelperLibrary;
using AVCUMPlatform.HelperLibrary.Cache;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AVCUMPlatform.DingTalkService.Model
{
    public class DingTalkToken
    {
        /// <summary>
        /// 单例
        /// </summary>
        private static DingTalkToken instance = new DingTalkToken();
        /// <summary>
        /// 锁
        /// </summary>
        private object sync_obj = new object();
        /// <summary>
        /// 微信应用id
        /// </summary>
        private string _appId { get; set; }
        /// <summary>
        /// 微信密钥
        /// </summary>
        private string _appSecret { get; set; }
        /// <summary>
        /// 缓存键
        /// </summary>
        private string cacheKey_Token = "DingCacheToken";
        /// <summary>
        /// 缓存实例
        /// </summary>
        ICache cache = CacheFactory.GetCacheInstance();
        /// <summary>
        /// 缓存模型
        /// </summary>
        private CacheEntity cacheWxEntity = null;

        /// <summary>
        /// 获取单例
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="appsecret"></param>
        /// <returns></returns>
        public static DingTalkToken GetInstance(string appid, string appsecret)
        {
            instance._appId = appid;
            instance._appSecret = appsecret;
            return instance;
        }

        /// <summary>
        /// token
        /// </summary>
        public string AccessToken
        {
            get
            {
                lock (sync_obj)
                {
                    DoGetToken();
                }
                return cacheWxEntity.Content;
            }
        }

        /// <summary>
        /// 获取token 方法
        /// </summary>
        private void DoGetToken()
        {
            try
            {
                if (cache.IsExists(cacheKey_Token + _appId))
                {
                    cacheWxEntity = cache.Get<CacheEntity>(cacheKey_Token + _appId);
                }
                else
                {
                    cacheWxEntity = new CacheEntity() { ElapsedAt = DateTime.Now, UpdateTime = DateTime.Now };
                }

                if (DateTime.Now >= cacheWxEntity.ElapsedAt)
                {
                    string url = "https://api.dingtalk.com/v1.0/oauth2/accessToken";
                    var param = new
                    {
                        appKey = _appId,
                        appSecret = _appSecret
                    };
                    var token = HTTPHelper.Post<DingTokenEntity>(url, param);
                    if (token.expireIn > 0)
                    {
                        int expireSeconds = token.expireIn - 300;
                        cacheWxEntity.Content = token.accessToken;
                        cacheWxEntity.ElapsedAt = DateTime.Now.AddSeconds(expireSeconds);
                        cacheWxEntity.UpdateTime = DateTime.Now;
                        cache.Remove(cacheKey_Token + _appId);
                        cache.Set(cacheKey_Token + _appId, cacheWxEntity, TimeSpan.FromSeconds(expireSeconds));
                    }
                }
            }
            catch (Exception ex)
            {
                Log.WriteException(ex);
            }
            
        }
    }
}
